<?php

namespace app\command\controller;

use app\common\func\Lib;
use app\common\func\Tools;
use app\common\model\EquipFigure;
use app\common\model\Policy;
use app\common\model\StandardRecord;
use think\Controller;

//海科
class Hk extends Controller
{
    protected $baseUrl = "./trade_log/hk/";

    //订单通知
    public function index()
    {
        $data = request()->param();
        if (is_string($data)) {
            $data = json_decode($data, true);
        }
        if (is_array($data)) {
            $data = $data;
        }
        $data = $data['data'];
        $data = json_decode($data, true);
        $sn = $data['snNo'];
        $orderNum = $data['logNo'];
        $equip = Lib::getEquip($sn);
        $order = \app\common\model\transaction\Hk::where(["order_num" => $orderNum])->find();
        if ($equip && !$order) {
            try {
                $rate = $data['feeRate'];
                $merchantName = $data['mercNm'];
                $tranAmount = $data['txnAmt'];

                $hk = new \app\common\model\transaction\Hk();
                $hk->agent_id = "000";
                $hk->merchant_id = $data['mercId'];
                $hk->order_num = $orderNum;
                $hk->sn = $sn;
                $hk->terminal = $data['trmNo'];
                $hk->trading_time = strtotime($data['txnTm']);
                $hk->transaction_amount = $tranAmount;
                $hk->transaction_type = $data['txnCd'];
                $hk->tran_fee_flag = $data['txnFeeFlg'];
                $hk->business_type = $data['txnBusTyp'];
                $hk->transaction_result = $data['ttxnSts'];
                $hk->card_num = $data['crdNo'];
                $hk->card_type = $data['crdFlg'];
                $hk->merchant_fee = $data['mercFeeAmt'];
                $hk->batch_no = $data['batNo'];
                $hk->trace_no = $data['cseqNo'];
                $hk->merchant_name = $merchantName;
                $hk->transaction_rate = $rate;
                $hk->c_rate = $data['ccardTfee'];
                $hk->d_rate = $data['dcardTfee'];
                $hk->settle_type = isset($data['stlTyp']) ? $data['stlTyp'] : 0;
                $hk->gather_type = "NORMAL";
                $hk->save();

                //分红交易存储
                \app\ports\controller\Trans::instance()->pro_real_time_trans($hk->toArray());

                //设备统计信息
//                $tranType = Lib::getTransactionTypeByCode($data['txnCd']);
                $cardTypeId = Tools::getCardTypeCode()[$data['crdFlg']]['id'];

                $policy = Policy::where(["product_id"=>$equip->product_id])->find();
                if ($policy) {
//                    $rateBool = false;
//                    $tran = explode(",", $policy['transaction_type_ids']);
                    $card = explode(",", $policy['card_type']);
//                    $rateList = \app\common\func\Order::getRateByIds($policy['rate_ids']);
//                    if (count($rateList) > 0) {
//                        foreach ($rateList as $k => $v) {
//                            if (($v->type == 1 && $v->rate == $rate) || ($v->type == 2 && $rate > $v->start && $rate < $v->end)) {
//                                $rateBool = true;
//                            }
//                        }
//                    }
                    //贷记卡的任何交易都计算到达标收益中
                    if (in_array($cardTypeId, $card)) {
                        $recordList = \app\common\func\Order::getRecordBySn($sn);
                        if (count($recordList)) {
                            $day = $hk->trading_time;
                            foreach ($recordList as $k => $v) {
                                if ($v->status ==0 && $v->start_day <= $day && $v->end_day >= $day) {
                                    $v->total_money += $tranAmount;
                                    $v->save();
                                } else if ($day > $v->end_day && $v->total_money < $v->require_money) {
                                    $v->status = 2;
                                    $v->save();
                                }
                            }
                        }
                    } else {
                        $hk->handle_state = 3;
                        $hk->handle_remark = "卡类型不符合";
                        $hk->save();
                    }
                }

            } catch (\Exception $e) {
                file_put_contents($this->baseUrl . "hk_tran_log" . date("Ym") . ".txt", "-------------------" . date("Y-m-d H:i:s") . "-----------------" . PHP_EOL, FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl . "hk_tran_log" . date("Ym") . ".txt", "data:" . json_encode($data) . PHP_EOL, FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl . "hk_tran_log" . date("Ym") . ".txt", "error:" . $e->getMessage() . PHP_EOL, FILE_APPEND | LOCK_EX);
            }
        }
    }

    //商户绑定通知
    public function binds()
    {
        $data = request()->param();
        if (is_string($data)) {
            $data = json_decode($data, true);
        }
        if (is_array($data)) {
            $data = $data;
        }

        $data = $data['data'];
        $data = json_decode($data, true);

        $sn = $data['snNo'];
        $equip = Lib::getEquip($sn);

        if ($equip && $equip->binding_time == 0) {
            try {
                $bindTime = strtotime($data['tmBindTm']);
                $equip->binding_time = $bindTime;
                $equip->active_time = $bindTime;
                $equip->user_info = $data['corpNm'];
                $equip->status = 1;
                $equip->save();

                //设备入库180天内绑定激活才给达标奖励
                if(($equip->active_time - $equip->create_time) / (60 * 60 * 24) <= 180){
                    $policy = Policy::where(["product_id" => $equip->product_id])->find();
                    if($policy){
                        $standardList = \app\common\func\Order::getStandardByPolicy($policy->id);
                        if (count($standardList) > 0) {
//                            $recordData = [];
                            foreach ($standardList as $k => $v) {
                                $startTime = $v->day_start == 0 ? 0 : $v->day_start - 1;
                                $startDay = strtotime("+" . $startTime . " day", $equip->active_time);
                                $endDay = strtotime("+" . $v->day_limit . " day", $equip->active_time);
                                $recordData = [
                                    "user_id" => $equip->main_id,
                                    "sn" => $sn,
                                    "start_day" => $startDay,
                                    "end_day" => $endDay,
                                    "require_money" => $v->money,
                                    "reward" => $v->reward,
                                ];

                                $record = StandardRecord::where(['sn' => $sn,"start_day" => $startDay,"end_day" => $endDay])->find();
                                if(!$record){
                                    $records = new StandardRecord();
                                    $records->save($recordData);
                                }

                                //查找是否有重复数据并进行处理
                                $count = StandardRecord::where(['sn' => $sn,"start_day" => $startDay,"end_day" => $endDay])->order("id desc")->select();
                                if(count($count) > 1){
                                    $id = $count[0]->id;
                                    StandardRecord::where(['id' => $id])->delete();
                                }
                            }
//                            usleep(500);
//
//                            $record = StandardRecord::where(['sn' => $sn])->find();
//                            if(!$record){
//                                $records = new StandardRecord();
//                                $records->saveAll($recordData);
//                            }
                        }
                    }
                }

                //减少调拨机构库存
//                    Tools::updateStocks($equip->main_type, $equip->main_id, $equip->product_id, 2, [$sn], "设备绑定减少库存");
            } catch (\Exception $e) {
                file_put_contents($this->baseUrl . "hk_bind_log" . date("Ym") . ".txt", "-------------------" . date("Y-m-d H:i:s") . "-----------------" . PHP_EOL, FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl . "hk_bind_log" . date("Ym") . ".txt", "info:" . json_encode($data) . PHP_EOL, FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl . "hk_bind_log" . date("Ym") . ".txt", "errorInfo:" . $e->getMessage() . PHP_EOL, FILE_APPEND | LOCK_EX);
            }
        }
    }
}
